package com.kaifamiao.trace;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Logger;

@WebServlet( "/url/rewrite" )
public class UrlRewriteServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void service(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        logger.info( "cookie: " + request.getHeader( "cookie" ) );

        HttpSession session = request.getSession();
        logger.info( "session is new: " + session.isNew() );

        String path = "/session/counter?letter=hello" ;
        logger.info( path );

        // 如果使用了新的会话对象，
        // 并且在请求头中未获取到 jsessionid 对应的 cookie
        // 则需要对 url 进行重写
        path = response.encodeURL( path );
        // path = response.encodeRedirectURL( path );
        logger.info( path );

        response.sendRedirect( path );
    }
}
